package com.sanqing.main;
import javax.swing.*;

import com.sanqing.dao.Dao;
import com.sanqing.iframe.BookLoginIFrame;
import com.sanqing.model.RecommenderInfo;
import com.sanqing.model.common;

import javax.swing.border.BevelBorder;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import com.sanqing.model.*;


public class ReaderFrame extends JFrame {
    private static final JDesktopPane DESKTOP_PANE = new JDesktopPane();// 桌面窗体
    private static final int ICON_WIDTH = 24;  // 图标宽度
    private static final int ICON_HEIGHT = 24; // 图标高度

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());// 设置系统界面外观
            SwingUtilities.invokeLater(() -> {
                BookLoginIFrame loginFrame = new BookLoginIFrame();
                loginFrame.setVisible(true);
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    	//ReaderFrame f=new ReaderFrame();
    }

    public static void addIFame(JInternalFrame iframe) {// 添加子窗体的方法
        DESKTOP_PANE.add(iframe);// 新增子窗体
    }

    public ReaderFrame() {
        super(); // 调用父类构造方法
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // 关闭按钮处理事件

        // 设置窗口位置和大小
        Toolkit tool = Toolkit.getDefaultToolkit();
        Dimension screenSize = tool.getScreenSize();
        setSize(900, 700);
        setLocation((screenSize.width - getWidth()) / 2,
                (screenSize.height - getHeight()) / 2);

        setTitle("读者借阅系统-"+common.UserName);

        // 设置菜单栏
        JMenuBar menuBar = createMenu();
        setJMenuBar(menuBar);

        // 设置工具栏
        JToolBar toolBar = createToolBar();
        getContentPane().add(toolBar, BorderLayout.NORTH);
        
        // 设置背景图片
        try {
            // 加载背景图片
            ImageIcon backgroundIcon = new ImageIcon("res/Readerback.jpg");

            // 创建一个显示背景图片的标签
            final JLabel backgroundLabel = new JLabel(backgroundIcon);

            // 确保标签随窗口大小变化而调整
            DESKTOP_PANE.addComponentListener(new ComponentAdapter() {
                public void componentResized(ComponentEvent e) {
                    // 调整标签大小以适应窗口
                    backgroundLabel.setSize(DESKTOP_PANE.getSize());

                    // 调整图片大小以适应标签
                    if (backgroundIcon != null && backgroundIcon.getImage() != null) {
                        Image scaledImage = backgroundIcon.getImage().getScaledInstance(
                                DESKTOP_PANE.getWidth(),
                                DESKTOP_PANE.getHeight(),
                                Image.SCALE_SMOOTH
                        );
                        backgroundLabel.setIcon(new ImageIcon(scaledImage));
                    }
                }
            });

            // 将背景标签添加到桌面面板的最底层
            DESKTOP_PANE.add(backgroundLabel, new Integer(Integer.MIN_VALUE));

            // 初始化背景标签大小
            backgroundLabel.setSize(DESKTOP_PANE.getSize());

        } catch (Exception e) {
            // 如果加载图片失败，显示错误信息
            JLabel errorLabel = new JLabel("无法加载背景图片: " + e.getMessage());
            errorLabel.setHorizontalAlignment(JLabel.CENTER);
            errorLabel.setVerticalAlignment(JLabel.CENTER);
            DESKTOP_PANE.add(errorLabel, new Integer(Integer.MIN_VALUE));
            e.printStackTrace();
        }

        // 添加桌面面板到主窗口
        getContentPane().add(DESKTOP_PANE);
        this.setVisible(true);
        List<RecommenderInfo> list=Dao.selectRecommenderInfo(common.UserName);
        for(int i=0;i<list.size();i++)
        {
        	String message="你推荐的ISBN为: "+ list.get(i).getISBN() + "的书籍已入馆,请及时查看";
            JOptionPane.showMessageDialog(null, message);
            int DeleteResult=Dao.DeleteRecommender(list.get(i).getISBN());
            
            // DeleteResult 判断暂定
        }
        // 当前用户借阅检查
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		String nowkDate = dateTimeFormatter.format(LocalDate.now().plusDays(6));

		List l = Dao.selectBorrow("select * from tb_borrow where readerISBN='" + BookLoginIFrame.getOperator().getISBN()
				+ "' and isback = 0 and backDate<='" + nowkDate + "'");
		int n = l.size();
		if (n > 0) {
			for (int i = 0; i < n; i++) {
				String message = "你的ISBN为: " + ((Borrow)l.get(i)).getBookISBN() + "的书籍有快超时或已经超时未归还的书";
				JOptionPane.showMessageDialog(null, message, "提示", JOptionPane.PLAIN_MESSAGE);
			}

		}

		common.check(); // 检查预约信息

		l = Dao.selectReserve("select * from tb_reserve where reserveDate IS NOT NULL and readerISBN='"+BookLoginIFrame.getOperator().getISBN()+"'");
		n = l.size();
		//System.out.println(n);
		if (n > 0) {
			for (int i = 0; i < n; i++) {
				String message = "你预约的ISBN为: " + ((Reserve)l.get(i)).getbookISBN() + "的图书已可以借阅";
				JOptionPane.showMessageDialog(null, message, "提示", JOptionPane.PLAIN_MESSAGE);
			}

		}
    }

    // 调整图标大小的辅助方法
    private ImageIcon resizeIcon(ImageIcon originalIcon, int width, int height) {
        if (originalIcon == null) return null;
        Image image = originalIcon.getImage();
        Image resizedImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        return new ImageIcon(resizedImage);
    }
    // 创建菜单栏的方法
    private JMenuBar createMenu() {
        JMenuBar menuBar = new JMenuBar();
        menuBar.setFont(new Font("宋体", Font.PLAIN, 14));

        JMenu BookManageMenu = new JMenu("书籍管理");
        BookManageMenu.setFont(new Font("宋体", Font.BOLD, 14));
        JMenuItem BookMenuItem = new JMenuItem(MenuActions.R_BOOK_INFO);
        BookManageMenu.add(BookMenuItem);
        // 借阅管理菜单
        JMenu borrowManageMenu = new JMenu("借阅管理");
        borrowManageMenu.setFont(new Font("宋体", Font.BOLD, 14));
        JMenuItem borrowMenuItem = new JMenuItem(MenuActions.R_BORROW);
        JMenuItem giveBackMenuItem = new JMenuItem(MenuActions.R_GIVE_BACK);
        JMenuItem searchMenuItem = new JMenuItem(MenuActions.R_BOOK_SEARCH);
        JMenuItem reserveMenuItem = new JMenuItem(MenuActions.R_BOOK_RESERVE);
        JMenuItem revokereserveMenuItem = new JMenuItem(MenuActions.R_reserve_revoke);
        borrowManageMenu.add(borrowMenuItem);
        borrowManageMenu.add(reserveMenuItem);
        borrowManageMenu.add(giveBackMenuItem);
        borrowManageMenu.add(searchMenuItem);
        borrowManageMenu.add(revokereserveMenuItem);

        JMenu UserManageMenu = new JMenu("用户体验");
        UserManageMenu.setFont(new Font("宋体", Font.BOLD, 14));
        JMenuItem NewbookMenuItem = new JMenuItem(MenuActions.Book_Recommend);
       
        UserManageMenu.add(NewbookMenuItem);

        menuBar.add(BookManageMenu);
        menuBar.add(borrowManageMenu);
        menuBar.add(UserManageMenu);

        return menuBar;
    }
    // 创建工具栏的方法 - 添加了工具栏提示
    private JToolBar createToolBar() {
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);
        toolBar.setBorder(new BevelBorder(BevelBorder.RAISED));

        // 添加工具栏按钮，使用调整后的图标并设置提示文本
        addToolBarButton(toolBar, MenuActions.R_BOOK_INFO, "res/bookinfo.jpg", "查看书籍");
        addToolBarButton(toolBar, MenuActions.R_BOOK_SEARCH, "res/bookSearch.jpg", "搜索书籍");
        addToolBarButton(toolBar, MenuActions.R_BORROW, "res/bookBorrowtb.jpg", "图书借阅");
        addToolBarButton(toolBar, MenuActions.R_BOOK_RESERVE, "res/bookreserve.jpg", "图书预约");
        addToolBarButton(toolBar, MenuActions.R_GIVE_BACK, "res/bookBrrow.jpg", "图书归还");
        addToolBarButton(toolBar, MenuActions.Book_Recommend, "res/bookRecommend.jpg", "图书荐购");

        return toolBar;
    }

    // 添加工具栏按钮的辅助方法 - 增加了提示文本参数
    private void addToolBarButton(JToolBar toolBar, Action action, String iconPath, String toolTipText) {
        JButton button = new JButton(action);
        button.setIcon(resizeIcon(new ImageIcon(iconPath), ICON_WIDTH, ICON_HEIGHT));
        button.setHideActionText(true);
        button.setToolTipText(toolTipText);  // 设置提示文本
        toolBar.add(button);
    }

}